import Taro, { Component } from '@tarojs/taro'
import { Text, View, ScrollView } from '@tarojs/components'
import { getCurrencyTime } from '@/api/commonApi'
import moment from '@/assets/js/moment.min'
import lodash from '@/utils/lodash'
import classNames from 'classnames'
import './index.scss'
import { getFreightConfig } from "@/utils/storage"

const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
const prefixCls = 'reserve-select'
export default class ReserveSelect extends Component {
  state: any
  props: any
  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    this.state = {
      current: 0,
      dateKey: '',
      dateList: [],
      timeKey: '',
      timeList: [],
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.isOpened !== nextProps.isOpened && nextProps.isOpened) {
      const { value='' } = nextProps
      getCurrencyTime().then(({ data }) => {
        const current = moment(data * 1000)
        const time = current.format("YYYY-MM-DD HH:mm")
        const dateKey = !!value ? value.split(" ")[0] : current.format("YYYY-MM-DD")
        this.setState({
          current: time,
          dateKey,
          timeKey: !!value ? value : ''
        }, () => {
          this.setState({
            timeList: this.getTime(dateKey),
            dateList: this.getDate(time)
          })
        })
      })
    }
  }

  //  获取日期
  getDate(timestamp) {
    const current = moment(timestamp)
    const dateList:any = []
    for (let i = 0; i < 23; i++) {
      dateList.push({
        DD: current.format("DD"),
        MM: current.format("MM"),
        YYYY: current.format("YYYY"),
        week: weeks[current.weekday()],
        timestamp: current.format("YYYY-MM-DD HH:mm")
      })
      current.add(1, 'days')
    }
    return dateList
  }

  //  获取时间
  getTime(timestamp) {
    // console.log(moment('2010-10-20 14:14:11').isBetween('2010-10-20 12:13:12', '2010-10-20 14:13:12'))
    const timeArr = (getFreightConfig('reserveTime') || '').split(' - ')
    const cur = moment(this.state.current)
    const start = (moment(timestamp).format("YYYY-MM-DD") !== cur.format("YYYY-MM-DD")) ? moment().format(`YYYY-MM-DD ${lodash.head(timeArr)}`) : cur.add(1, 'hour').minute(0).second(0).format(`YYYY-MM-DD HH:mm:ss`)
    const end = moment().format(`YYYY-MM-DD ${lodash.last(timeArr)}`)
    // console.log(start)
    // console.log(end)
    const timeList:any = []
    const countTime = moment(start)
    for (let i = 0; i < 48; i++) {
      const time = countTime.format("HH:mm:ss")
      if (moment(countTime.format('YYYY-MM-DD HH:mm:ss')).isBetween(start, end)) {
        timeList.push(time)
      }
      // console.log(countTime.format(`YYYY-MM-DD ${time}`))
      // console.log(end)
      // console.log(countTime.format(`YYYY-MM-DD HH:mm:ss`).isBetween(start, end))
      // if (!countTime.format(`YYYY-MM-DD HH:mm:ss`).isBetween(start, end)) break
      countTime.add(30, 'minutes')
    }
    return timeList
  }

  //  选择日期
  onClickDate({ timestamp, YYYY, MM, DD }) {
    this.setState({
      dateKey: `${YYYY}-${MM}-${DD}`
    }, () => {
      this.setState({
        timeList: this.getTime(timestamp)
      })
    })
  }

  //  选择时间
  onClickTime(time) {
    const { onConfirm } = this.props
    const { dateKey, timeKey } = this.state
    const key = `${dateKey} ${time}`
    const checked = key !== timeKey ? key : ''
    this.setState({
      timeKey: checked
    }, () => {
      onConfirm && onConfirm(checked)
    })
  }

  render() {
    const { onClose, isOpened } = this.props
    const { dateKey, dateList, timeKey, timeList } = this.state
    const bool = isOpened ? 'enter' : 'leave'
    // @ts-ignore
    return (<View catchtouchmove>
      <View className={`xf-overlay xf-fade-${bool}`} onClick={() => onClose()}/>
      <View className={classNames(`xf-popup xf-popup--bottom xf-popup--round ${prefixCls}`, {
        [`xf-slide-bottom xf-slide-${bool}`]: !isOpened,
      })}>
        <View className={`${prefixCls}__head f-g-5 thin-border__b`}>
          <View className={`${prefixCls}__head-title`}>选择预订送达时间</View>
          <View className={`${prefixCls}__head-close f-g-5 bnn-icon`} onClick={() => onClose()}>&#xe646;</View>
        </View>
        <View className={`${prefixCls}__body`}>
          <ScrollView scrollY className={`${prefixCls}__date-list`}>
            {
              dateList.map((date, key) => {
                return (<View key={key} className={classNames(`${prefixCls}__date-item f-g-5`, {
                  [`${prefixCls}__date-active`]: dateKey === `${date.YYYY}-${date.MM}-${date.DD}`
                })} onClick={this.onClickDate.bind(this, date)}>
                  {date.MM}-{date.DD}（{date.week}）
                </View>)
              })
            }
          </ScrollView>
          <ScrollView scrollY className={`${prefixCls}__time-list`}>
            {
              timeList.map((time, key) => {
                const checked = timeKey === `${dateKey} ${time}`
                return (<View key={key} className={classNames(`${prefixCls}__time-item f-g-4 thin-border__b`, {
                  [`${prefixCls}__time-active`]: checked
                })} onClick={this.onClickTime.bind(this, time)}>
                  {time}
                  {checked && <Text className={`${prefixCls}__time-fee`}>（点击取消）</Text>}
                  {checked && <Text className={`${prefixCls}__time-icon bnn-icon f-g-5`}>&#xe645;</Text>}
                </View>)
              })
            }
          </ScrollView>
        </View>
      </View>
    </View>)
  }
}
